import React, { useState, useEffect } from "react";
import { MemberEntity } from "../model/member";
import { getMembersCollection } from "../api/memberApi";

// 自定义 hooks 函数封装 - 数据请求
const useMemberCollection = () => {
    const [memberCollection, setMemberCollection] =
        useState<MemberEntity[]>([])
    const loadMemberCollection = () => {
        getMembersCollection()
            .then(
                memberCollection => setMemberCollection(memberCollection)
            )
    }
    return {
        memberCollection,
        loadMemberCollection
    }
}

// 不需要外部传东西 <{}>
const MemberTableComponent: React.FC<{}> = () => {
    // useMemberCollection(); 自定义 hooks 函数封装
    const { memberCollection, loadMemberCollection } =
        useMemberCollection();
    useEffect(() => {
        loadMemberCollection();
    }, [])
    return (
        <>
            <table>
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Avter</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        memberCollection.map(member => (
                            <MemberRow key={member.id} member={member} />
                        ))
                    }
                </tbody>
            </table>
        </>
    )
}


const MemberRow = ({ member }: { member: MemberEntity }) => {
    return (
        <tr>
            <td>
                <img src={member.avatar_url} style={{ maxWidth: "10rem" }} />
            </td>
            <td>
                <span>{member.id}</span>
            </td>
            <td>
                <span>{member.login}</span>
            </td>
        </tr>
    )
}

export default MemberTableComponent